// chapterFolder.js
function folderHtmlWithData(data){
	var imgPath = folderImagePathWithUrlPath(data);
	var source_url = data.sourceUrl;
	return '<div class="weui_cell base_content_color_font folder_file_cell" vid="'+data.vid+'" file_name="'+data.names+'" file_path="'+data.filepath+'" is_encr="'+data.is_encr+'" baidu_cloud_id="'+data.baidu_cloud_id+'" baidu_cloud_id_url="'+data.baidu_cloud_id_url+'" source_url="'+source_url+'">'+
				'<div class="weui_cell_hd">'+
					'<img src="'+imgPath+'" alt="" class="chapter_cell_left_icon">'+
				'</div>'+
				'<div class="weui_cell_bd weui_cell_primary">'+
					'<p class="base_dark_grey base_tag_font">'+
						'<span class="chapter_title">'+data.names+'</span>'+
					'</p>'+
				'</div>'+
			'</div>';
}
function folderImagePathWithUrlPath(data){
	// var filePath = data.filename;
	var filePath = data.names;
	if (filePath == undefined || filePath == null || filePath == '') {
		return '../../image/icon_wenjia01.png';
	}
	var fileSuffix = folderFileSuffixWithPath(filePath);
	if (fileSuffix == '.doc' || fileSuffix == '.docx') {
		return '../../image/icon_chapter_doc.png';
	}else if(fileSuffix == '.pdf'){
		return '../../image/icon_chapter_pdf.png';
	}else if(fileSuffix == '.xls' || fileSuffix == '.xlsx'){
		return '../../image/icon_chapter_excel.png';
	}else if(fileSuffix == '.ppt' || fileSuffix == '.pptx'){
		return '../../image/icon_chapter_ppt.png';
	}else if(fileSuffix == '.png' || fileSuffix == '.jpg' || fileSuffix == '.jpeg' || fileSuffix == '.bmp' || fileSuffix == '.gif'){
		return '../../image/icon_chapter_img.png';
	}else if(fileSuffix == '.mp4' || fileSuffix == '.avi' || fileSuffix == '.rmvb' || fileSuffix == '.3gp' || fileSuffix == '.flv' || fileSuffix == '.wmv'){
		return '../../image/09.png';
	}else{
		return '../../image/icon_wenjia01.png';
	}
}
function folderFileSuffixWithPath(path){
	// var result =/\.[^\.]+/.exec(path);
	var index1 = path.lastIndexOf(".");
	var index2 = path.length;
	var result = path.substring(index1,index2);
	// var nameArr = path.split('.');
	// var result = '.' + nameArr.pop();//取出数组最后一个元素
	return result;
}
function isExitsFunction(funcName) {
	try {
		if (typeof(eval(funcName)) == "function") {
		  	return true;
		}
	} catch(e) {}
	return false;
}
function setupFolderFileClick(){
	$('.folder_file_cell').unbind('click');
	$('.folder_file_cell').click(function(){
		var doc = $(this).attr('file_path');
		var title = $(this).attr('file_name');
		var is_encr = $(this).attr('is_encr');
		var vid = $(this).attr('vid');
		if (isExitsFunction('uploadChapterStudyRecord') == true) {
			//开始记录学习
			uploadChapterStudyRecord(vid);
		}
		//记录学习数据对象
		var extendData = {
			vid : vid
		};
		var source_url = $(this).attr('source_url');
		if (source_url != null && source_url != undefined && source_url != 'undefined' && source_url != '') {
			doc = source_url;
		}
		var baidu_cloud_id = $(this).attr('baidu_cloud_id');
		var baidu_cloud_id_url = $(this).attr('baidu_cloud_id_url');
		var arr = new Array('jpg', 'png', 'jpeg');
		var gifArr = new Array('gif', 'bmp');
		var arr1 = new Array('swf', 'mp4', 'flv', '3gp', 'mov', 'rmvb', 'avi', 'wmv', 'flv%22', 'mp4%22', 'mov%22', '3gp%22', 'rmvb%22', 'avi%22', 'wmv%22');
		var ext = doc.replace(/.+\./, "");
		if (gifArr.toString().indexOf(ext) > -1){
			openGif(doc, extendData);
		}else if (arr.toString().indexOf(ext) > -1) {
			openImage(doc, extendData);
		} else {
			if (arr1.toString().indexOf(ext) > -1) {
				var connectionType = api.connectionType;
	            if (connectionType != 'wifi' && connectionType != 'none') {
	            	api.confirm({
	                    title: '提示',
	                    msg: '您当前处于移动数据网络下，是否继续播放',
	                    buttons: ['确定', '取消']
	                }, function(ret, err) {
	                    var index = ret.buttonIndex;
	                    if (index == 1) {//确定
	                        pushToBaiDuPlayer(is_encr, baidu_cloud_id_url, doc, title, vid, 1);
	                    }
	                });
	            }else{
	            	pushToBaiDuPlayer(is_encr, baidu_cloud_id_url, doc, title, vid, 1);
	            }
			} else {
				if (api.connectionType == 'none') {
					api.toast({
						msg : '暂无网络，无法访问该内容'
					});
					return;
				}
				if (is_encr == 1 || is_encr == 2) {//加密
			        api.openWin({useWKWebView:true,
					    name: 'StudyWebBaiDuDoc_win',
					    url: '../Study/StudyWebBaiDuDoc_win.html',
					    pageParam: {
					        docId: baidu_cloud_id,
					        title: title,
					        vid: vid
					    },
					    slidBackEnabled : false
					});
				}else{
					api.openWin({useWKWebView:true,
						name : 'Student_FreeCourseDoc',
						url : '../Study/Student_FreeCourseDoc.html',
						pageParam : {
							title : title,
							doc : doc,
							cid : api.pageParam.courseid,
		                    vid : vid,
		                    pid : api.pageParam.planid,
							sourceurl : window.location.pathname,
					        sourcetitle : document.title
						},
						slidBackEnabled : false
					});
				}
				// if (doc != 'undefined' && doc != undefined && doc != null && doc != '') {
				// 	api.openWin({useWKWebView:true,
				// 		name : 'Student_FreeCourseDoc',
				// 		url : '../Study/Student_FreeCourseDoc.html',
				// 		pageParam : {
				// 			title : title,
				// 			doc : doc,
				// 			cid : api.pageParam.courseid,
		  //                   vid : vid,
		  //                   pid : api.pageParam.planid,
				// 			sourceurl : window.location.pathname,
				// 	        sourcetitle : document.title
				// 		}
				// 	});
				// }else{
				// 	if (is_encr == 1) {//加密
				// 		var CFBaiDuDoc = api.require('CFBaiDuDoc');
				//         CFBaiDuDoc.startDocActivityForResult({
				//             docId:baidu_cloud_id,//文档ID
				//             title:title,//文档标题
				//             token:"TOKEN",//文档token，离线加载时不验证。
				//             host:"BCEDOC",//文档所属站点
				//             docType:"doc" //文档类型，可取值为ppt 和 doc
				//         },function(){
				//         });
				// 	}else{
				// 		api.toast({
				// 		    msg: '文件打开失败'
				// 		});
				// 	}
				// }
			}
		}
		//停止事件传递
		event.stopPropagation();
	});
}
function setupFolderFCellClick(chapterid){
	if ($('#'+chapterid).hasClass('show-folder')) {
		$('#'+chapterid).removeClass('show-folder');
		$('#'+chapterid).addClass('hide-folder');
		$('#folder_file_div'+chapterid).hide();
		$('#folder_right_img'+chapterid).attr('src', '../../image/icon_bewrite_down.png');
	}else{
		if ($('#folder_file_div'+chapterid).html() == '') {//如果没内容则请求数据
			getFolderData(chapterid);
		}
		$('#'+chapterid).removeClass('hide-folder');
		$('#'+chapterid).addClass('show-folder');
		$('#folder_file_div'+chapterid).show();
		$('#folder_right_img'+chapterid).attr('src', '../../image/icon_bewrite_up.png');
	}
}
function setupFolderFile(chapterid, files){
	var filesHtmlString = '';
	for (var i = 0; i < files.length; i++) {
		var fileData = files[i];
		var filePath = fileData.realurl;
		filePath = filePath.replace('bcs.duapp.com/cfnetdoc', 'cfnetdoc.cfnet.org.cn');
		var filename = filePath.substr(filePath.lastIndexOf('\/')+1);
		fileData["filename"] = filename;
		fileData["filepath"] = filePath;
		fileData["vid"] = chapterid;
		$('#folder_file_div'+chapterid).append(folderHtmlWithData(fileData));
	}
	setupFolderFileClick();
}
function getFolderData(chapterid){
	var pageParam = api.pageParam;
	var param = {
		uid : $api.getStorage('cfnetppuid'),
		jid : $api.getStorage('cfnetppjxid'),
		cid : pageParam.courseid,
		vid : chapterid,
		pid : pageParam.planid
	};
	cfnetppPOST(url_getfolder,
	param,
	true,
	function(data, status){
		if (status == 'success') {
			if (data.status == true && data.code == 200) {
				var json = data.json;
				var folderFiles = json;
				var fileList = folderFiles.filepath;
				if (fileList != undefined && fileList != null && fileList != '' && fileList.constructor == Array && fileList.length > 0) {
					setupFolderFile(chapterid, fileList);
				}else{
					api.toast({
					    msg: '该文件夹暂无内容'
					});
				}
			}else{
				api.toast({
				    msg: '该文件夹暂无内容'
				});
			}
		}else{
			api.toast({
			    msg: '加载失败'
			});
		}
	});
}